<template>
  <div class="app-container">
    <el-form class="formBox formBox1 searchForm" :model="queryParams" ref="queryParams" size="small" :inline="true"
      v-show="showSearch" label-width="68px">
      <el-form-item label="顾客ID" prop="patientId">
        <el-input v-model="queryParams.patientId" placeholder="顾客ID" clearable style="width: 100px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="顾客编号" prop="visitNum">
        <el-input v-model="queryParams.visitNum" placeholder="请输入顾客编号" clearable style="width: 160px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="姓名" prop="patientName">
        <el-input v-model="queryParams.patientName" placeholder="顾客姓名" clearable style="width: 100px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="patientPhone">
        <el-input v-model="queryParams.patientPhone" placeholder="请输入顾客手机号" clearable style="width: 160px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证号" prop="idNum">
        <el-input v-model="queryParams.idNum" placeholder="请输入顾客身份证号" clearable style="width: 180px"
          @focus="getSFZToSearch" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form class="formBox formBox1 searchForm" :model="patientItem" ref="patientItem" size="small" :inline="true"
      v-show="showSearch" label-width="68px">
      <!--      <div class="contentBox">-->
      <!--        <div class="contentBoxLeft">-->
      <!--          <div class="line"></div>-->
      <!--          <div class="name">顾客信息</div>-->
      <!--        </div>-->
      <!--        <div class="contentBoxRight">-->
      <!--          <el-button type="primary" plain icon="el-icon-s-custom" size="mini" @click="goDetail">顾客详情</el-button>-->
      <!--          <el-button type="success" plain icon="el-icon-picture" size="mini" @click="goMorePicture">更多照片</el-button>-->
      <!--        </div>-->
      <!--      </div>-->
      <el-row>
        <el-form-item label="顾客ID" prop="patientId">
          <el-input v-model="patientItem.patientId" placeholder="顾客ID" clearable style="width: 100px" :disabled="true" />
        </el-form-item>
        <el-form-item label="顾客编号" prop="visitNum">
          <el-input v-model="patientItem.visitNum" placeholder="顾客编号" clearable style="width: 160px" :disabled="true" />
        </el-form-item>
        <el-form-item label="姓名" prop="patientName">
          <el-input v-model="patientItem.patientName" placeholder="顾客姓名" clearable style="width: 100px"
            :disabled="true" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select :disabled="true" v-model="patientItem.sex" placeholder="性别" clearable style="width: 100px">
            <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="birthDate">
          <el-input v-model="patientItem.birthDate" placeholder="顾客年龄" clearable style="width: 100px" :disabled="true" />
        </el-form-item>
        <el-form-item label="手机号" prop="patientPhone">
          <el-input v-model="patientItem.patientPhone" placeholder="顾客手机号" clearable style="width: 160px"
            :disabled="true" />
        </el-form-item>


      </el-row>
      <el-form-item label="状态" prop="status">
        <el-select v-model="patientItem.status" placeholder="诊断状态" clearable style="width: 100px" :disabled="true">
          <el-option v-for="dict in dict.type.sys_diagnosis_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="就诊门诊" prop="deptName">
        <el-input v-model="patientItem.deptName" placeholder="就诊门诊" clearable style="width: 160px" :disabled="true" />
      </el-form-item>
      <el-form-item label="顾客性质" prop="properties">
        <el-select v-model="patientItem.properties" placeholder="顾客性质" clearable style="width: 100px" :disabled="true">
          <el-option v-for="dict in dict.type.sys_patient_properties" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="顾客分类" prop="customerSort">
        <el-select v-model="patientItem.customerSort" placeholder="顾客分类" clearable style="width: 100px" :disabled="true">
          <el-option v-for="dict in dict.type.sys_patient_sort" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="医生诊断" prop="diagnosis">
        <el-input v-model="patientItem.doctorDiagnosis" type="textarea" :rows="1" placeholder="医生诊断" clearable
          style="width: 340px" :disabled="true" />
      </el-form-item>
      <el-form-item v-if="patientItem.patientId">
        <!--        <el-button type="primary" plain icon="el-icon-s-custom" size="mini"-->
        <!--                   @click="goDetail(patientItem.patientId)">顾客详情</el-button>-->
        <el-button type="success" plain icon="el-icon-picture" size="mini" @click="goMorePicture"
          v-hasPermi="['photoWorkstation:photoList:more']">更多照片({{ photoCount ? photoCount : 0 }})
        </el-button>
      </el-form-item>

    </el-form>

    <div class="formBox searchForm" v-loading="imageLoading">
      <div class="progressBox" v-if="imageLoading">
        <div class="lineTitle">共有 {{ uploadNum }} 张照片正在上传,请稍等...</div>
        <div class="lineBox" v-for="(item, index) in uploadFileLists" :key="index">
          <div class="indexBox">{{ index + 1 }}</div>
          <el-progress :percentage="item.progress"></el-progress>

        </div>
        <!--        <el-progress  :percentage="item.progress" v-for="(item, index) in uploadFileLists" :key="index"></el-progress>-->
      </div>
      <div >
        <el-row :gutter="10">
          <el-col :xs='24' :sm="24" :md="14" :lg="15" :xl="15">
            <el-form size="small" :inline="true" label-width="68px">
              <div class="contentDailog_contents_div">
                <el-form-item label="采集设备" prop="photoDevice">
                  <el-radio-group v-model="photoDevice" @input="radioChange">
                    <el-radio v-for="dict in dict.type.photo_upload_type" :key="dict.value" :label="dict.value">{{
                      dict.label
                    }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="" label-width="0px" class="noLabelItem" v-if="photoDevice == '0'">
                  <el-button type="primary" icon="el-icon-setting" style="margin-left:5px"
                    @click="openFeituSetting">霏图设置</el-button>
                </el-form-item>
                <el-form-item label="" label-width="0px" class="noLabelItem" v-if="photoDevice == '0'">
                  <el-button type="primary" icon="el-icon-download" style="margin-left:5px"
                             @click="checkFeituBrowser">选择照片</el-button>
                </el-form-item>
                <el-form-item label="" label-width="0px" class="noLabelItem" v-if="photoDevice == '1'">
                  <el-button type="primary" icon="el-icon-setting" style="margin-left:5px"
                    @click="openPhotoSetting">VISIA设置</el-button>
                </el-form-item>
                <el-form-item label="" label-width="0px" class="noLabelItem" v-if="photoDevice == '1'">
                  <el-button type="primary" icon="el-icon-download" style="margin-left:5px"
                    @click="checkBrowser">选择照片</el-button>
                </el-form-item>


                <el-form-item label="" label-width="0px" class="noLabelItem" v-if="photoDevice == '2'">

                  <el-button type="primary" icon="el-icon-setting" style="margin-left: 5px"
                    @click="openCameraSetting">照相机设置</el-button>
                </el-form-item>
                <el-form-item label="" label-width="0px" class="noLabelItem" v-if="photoDevice == '2'">
                  <el-button type="primary" icon="el-icon-download" style="margin-left: 5px"
                    @click="checkCameraBrowser">选择照片</el-button>
                </el-form-item>
                <el-form-item label="" label-width="0px" class="noLabelItem" style="margin-left:5px"
                  v-if="photoDevice == '2'">
                  <el-button type="primary" icon="el-icon-download" @click="goNewPage">自动获取照片</el-button>

                </el-form-item>
              </div>

            </el-form>
          </el-col>

          <el-col :xs='24' :sm="24" :md="10" :lg="9" :xl="9">
            <el-form class="formBox2"  size="small" :inline="true" label-width="68px">
            <div class="contentDailog_contents_div">
                <el-form-item label="照片编号:" prop="photoNum" v-if="photoDevice == '2' && patientItem.photoNum">
                    {{ patientItem.photoNum}}
                </el-form-item>
                <el-form-item label="录入日期" prop="photoUploadTime">
                    <el-date-picker v-model="photoUploadTime" align="left" @change="changeUploadTime"
                        class="idNumInput" type="datetime" placeholder="选择日期"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        :picker-options="photoPickerOptions">
                    </el-date-picker>
                </el-form-item>


                <el-form-item label="" label-width="0px" class="noLabelItem"
                        style="margin-left:5px">
                        <el-button v-if="photoDevice == '0'" type="primary"
                        @click="submitFeituUpload">提 交</el-button>
                        <el-button v-if="photoDevice == '1'" type="primary"
                        @click="submitVisiaUpload">提 交</el-button>
                        <el-button v-if="photoDevice == '2'" type="primary"
                        @click="submitCameraUpload">提 交</el-button>

                    </el-form-item>
            </div>
        </el-form>
        </el-col>

        </el-row>

      </div>
      <el-row class="photoImageContent" v-if="photoDevice == '0'">
        <el-col :xs='8' :sm="8" :md="8" :lg="8" :xl="8" v-for="(item, index) in feituImageInfo" :key="index">
          <div class="text-center">
            <div class="user-info-head">
              <el-image class="img-style" :src="item.faceUrl" :preview-src-list="feituSrcList"></el-image>

              <div class="rightNum">{{ index + 1 }}</div>
              <div class="rightIcon" @click="deleteFeituImg(index)">X</div>
              <div class="leftEnlarge" @click="replaceFeituImg(index)"><i class="el-icon-upload"></i></div>

            </div>
            <el-form class="photoImageContent_formBox" :model="item" ref="pictureForm" size="small"
              :label-width="device !== 'mobile' ? '78px' : '0px'">
              <el-form-item :label="device !== 'mobile' ? '光照类型' : ''" :class="device == 'mobile' ? 'noLabelItem' : ''">
                <el-select v-model="item.faceLight" disabled filterable placeholder="光照类型" clearable
                  class="photoImageContent_input">
                  <el-option v-for="dict in dict.type.photo_lighting_type" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="device !== 'mobile' ? '部位' : ''" :class="device == 'mobile' ? 'noLabelItem' : ''">
                <el-select v-model="item.facePart" filterable placeholder="部位" clearable class="photoImageContent_input">
                  <el-option v-for="dict in dict.type.sys_face_part" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
      <el-row class="photoImageContent" :gutter="10" v-if="photoDevice == '1'">
        <el-col :xs="8" :sm="6" :md="6" :lg="{ span: '4-8' }" :xl="{ span: '4-8' }"
          v-for="(item, index) in VisiaImageInfo" :key="index">
          <div class="text-center">
            <div class="user-info-head">
              <el-image class="img-style" :src="item.faceUrl" :preview-src-list="srcList"></el-image>

              <div class="rightNum">{{ index + 1 }}</div>
              <div class="rightIcon" @click="deleteImg(index)">X</div>
              <div class="leftEnlarge" @click="replaceImg(index)"><i class="el-icon-upload"></i>
              </div>

            </div>
            <el-form class="photoImageContent_formBox" :model="item" ref="pictureForm" size="small"
              :label-width="device !== 'mobile' ? '78px' : '0px'">
              <el-form-item :label="device !== 'mobile' ? '光照类型' : ''" :class="device == 'mobile' ? 'noLabelItem' : ''">
                <el-select v-model="item.faceLight" filterable placeholder="光照类型" clearable
                  class="photoImageContent_input">
                  <el-option v-for="dict in dict.type.photo_lighting_type" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="device !== 'mobile' ? '部位' : ''" :class="device == 'mobile' ? 'noLabelItem' : ''">
                <el-select v-model="item.facePart" filterable placeholder="部位" clearable class="photoImageContent_input">
                  <el-option v-for="dict in dict.type.sys_face_part" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>

      <el-row class="photoImageContent" :gutter="10" v-if="photoDevice == '2'">
        <el-col :xs="8" :sm="6" :md="6" :lg="{ span: '4-8' }" :xl="{ span: '4-8' }"
          v-for="(item, index) in cameraImageInfo" :key="index">
          <div class="text-center">
            <div class="user-info-head">
              <el-image class="img-styleCamera" fit="contain" :src="item.faceUrl"
                :preview-src-list="cameraSrcList"></el-image>

              <div class="rightNum">{{ index + 1 }}</div>
              <div class="rightIcon" @click="deleteCameraImg(index)">X</div>
              <div class="leftEnlarge" @click="replaceCameraImg(index)"><i class="el-icon-upload"></i></div>

            </div>
            <el-form class="photoImageContent_formBox" :model="item" ref="pictureForm" size="small"
              :label-width="device !== 'mobile' ? '78px' : '0px'">
              <el-form-item :label="device !== 'mobile' ? '光照类型' : ''" :class="device == 'mobile' ? 'noLabelItem' : ''">
                <el-select v-model="item.faceLight" disabled filterable placeholder="光照类型" clearable
                  class="photoImageContent_input">
                  <el-option v-for="dict in dict.type.photo_lighting_type" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="device !== 'mobile' ? '部位' : ''" :class="device == 'mobile' ? 'noLabelItem' : ''">
                <el-select v-model="item.facePart" filterable placeholder="部位" clearable class="photoImageContent_input">
                  <el-option v-for="dict in dict.type.sys_face_part" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>

      <el-dialog title="霏图设备设置" :visible.sync="feituSettingVisible" width="460px " center :close-on-click-modal="false"
        v-dialogDrag>
        <el-form :model="feituSettingFormCopy" label-width="100px">
          <el-form-item label="设备类型">
            <el-input :disabled="true" v-model="feituSettingFormCopy.settingType" style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="照片压缩质量">
            <el-input-number :min="0.1" :max="1" :precision="2" :step="0.01" v-model="feituSettingFormCopy.photoQuality"
              style="width: 250px"></el-input-number>
          </el-form-item>
          <el-form-item v-for="(item, index) in feituSettingFormCopy.photoSetting" :key="index">
            <span slot="label">
              第{{ index + 1 }}张
            </span>
            <el-select v-model="item.faceLight" filterable placeholder="光照类型" style="width: 120px" :clearable="true">
              <el-option v-for="dict in dict.type.photo_lighting_type" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
            <el-select v-model="item.facePart" filterable placeholder="部位" style="width: 120px;margin-left: 10px"
              :clearable="true">
              <el-option v-for="dict in dict.type.sys_face_part" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="confirmFeituSetting">确 定</el-button>
          <el-button @click="cancelFeituSetting">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog title="VISIA设备设置" :visible.sync="photoSettingVisible" width="460px " center :close-on-click-modal="false"
        v-dialogDrag>
        <el-form :model="photoSettingFormCopy" label-width="100px">
          <el-form-item label="设备类型">
            <el-input :disabled="true" v-model="photoSettingFormCopy.settingType" style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="照片压缩质量">
            <el-input-number :min="0.1" :max="1" :precision="2" :step="0.01" v-model="photoSettingFormCopy.photoQuality"
              style="width: 250px"></el-input-number>
          </el-form-item>
          <el-form-item label="照片张数">
            <el-input-number :min="1" v-model="photoSettingFormCopy.photoNumber" @change="photoNumberChange"
              style="width: 250px"></el-input-number>
          </el-form-item>
          <el-form-item v-for="(item, index) in photoSettingFormCopy.photoSetting" :key="index">
            <span slot="label">
              第{{ index + 1 }}张
            </span>
            <el-select v-model="item.faceLight" filterable placeholder="光照类型" style="width: 120px" :clearable="true">
              <el-option v-for="dict in dict.type.photo_lighting_type" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
            <el-select v-model="item.facePart" filterable placeholder="部位" style="width: 120px;margin-left: 10px"
              :clearable="true">
              <el-option v-for="dict in dict.type.sys_face_part" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="confirmSetting">确 定</el-button>
          <el-button @click="cancelSetting">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog title="照相机设备设置" :visible.sync="cameraSettingVisible" width="460px " center :close-on-click-modal="false"
        v-dialogDrag>
        <el-form :model="cameraSettingFormCopy" label-width="100px">
          <el-form-item label="设备类型">
            <el-input :disabled="true" v-model="cameraSettingFormCopy.settingType" style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="照片压缩质量">
            <el-input-number :min="0.1" :max="1" :precision="2" :step="0.01" v-model="cameraSettingFormCopy.photoQuality"
              style="width: 250px"></el-input-number>
          </el-form-item>
          <el-form-item label="照片张数">
            <el-input-number :min="1" v-model="cameraSettingFormCopy.photoNumber" @change="cameraNumberChange"
              style="width: 250px"></el-input-number>
          </el-form-item>
          <el-form-item v-for="(item, index) in cameraSettingFormCopy.photoSetting" :key="index">
            <span slot="label">
              第{{ index + 1 }}张
            </span>
            <el-select v-model="item.faceLight" filterable placeholder="光照类型" style="width: 120px" :clearable="true">
              <el-option v-for="dict in dict.type.photo_lighting_type" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
            <el-select v-model="item.facePart" filterable placeholder="部位" style="width: 120px;margin-left: 10px"
              :clearable="true">
              <el-option v-for="dict in dict.type.sys_face_part" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="confirmCameraSetting">确 定</el-button>
          <el-button @click="cancelCameraSetting">取 消</el-button>
        </div>
      </el-dialog>

    </div>
    <el-dialog title="选择顾客" :visible.sync="patientVisible" width="80%" :close-on-click-modal="false" v-dialogDrag>
      <div class="formBox">
        <el-table border v-loading="loading" style="width: 100%" :data="patientList">
          <el-table-column label="序号" align="center" type="index" width="50">
            <template slot-scope="scope">
              <span>{{ getIndex(scope.$index) }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="顾客ID" align="center" prop="patientId" :show-overflow-tooltip="true"
            width="100" />
          <el-table-column sortable label="顾客编号" align="center" prop="visitNum" width="160" />
          <el-table-column sortable label="顾客姓名" align="center" prop="patientName" :show-overflow-tooltip="true"
            width="100" />
          <el-table-column sortable label="顾客手机号" align="center" prop="patientPhone" :show-overflow-tooltip="true"
            width="120" />
          <el-table-column sortable label="性别" align="center" prop="sex" width="80">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
            </template>
          </el-table-column>
          <el-table-column sortable label="年龄" align="center" prop="birthDate" width="80" />
          <el-table-column sortable label="就诊门诊" align="center" prop="deptName" :show-overflow-tooltip="true" />
          <el-table-column sortable label="状态" align="center" prop="status" :show-overflow-tooltip="true" width="120">
            <!--              <template slot-scope="scope">-->
            <!--                <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />-->
            <!--              </template>-->
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == '0'" type="danger">
                <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
              </el-tag>
              <el-tag v-else-if="scope.row.status == '1'" type="warning">
                <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
              </el-tag>
              <el-tag v-else-if="scope.row.status == '3'" type="success">
                <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
              </el-tag>
              <el-tag v-else-if="scope.row.status == '4'">
                <dict-tag :options="dict.type.sys_diagnosis_status" :value="scope.row.status" />
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column sortable label="顾客性质" align="center" prop="properties" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_patient_properties" :value="scope.row.properties" />
            </template>
          </el-table-column>
          <el-table-column sortable label="登记人" align="center" prop="nickName" width="120"
            :show-overflow-tooltip="true" />
          <el-table-column sortable label="登记日期" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-caret-right" @click="confirmPatient(scope.row)">点击选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :pageSizes.sync="pageSizes" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getPatientList" />
      </div>
    </el-dialog>
    <el-dialog title="更多照片" :visible.sync="morePicsDialogVisible" :before-close="closeMorePicsDialog" :width="device !== 'mobile' ? '95%':'100%'" center
      :close-on-click-modal="false" v-dialogDrag class="nopaddingDailog" :class="device !== 'mobile' ? '':'active'">
      <morePics :patientId="patientItem.patientId" v-if="!!patientItem.patientId" :timer="timer"></morePics>
    </el-dialog>

  </div>
</template>
<script>
import { getVisit } from "@/api/patientRegistration/registrationList";
import store from "@/store";
import { mapGetters } from 'vuex'
// 导入的方法将使用文件系统
// 访问API或回退实现。
import {
  fileOpen,
  directoryOpen,
  fileSave,
  supported,
} from 'browser-fs-access';
import { uploadPhoto, getPhotoAllCountByPatientId, getPhotoAllCountByVisitNum } from "@/api/photoWorkstation/photoList";

import imgzip from "imgzip";
import { nanoid } from 'nanoid'
import cache from "@/plugins/cache";


import morePics from "@/views/photoWorkstation/photoList/morePics";
import { getDevice, startReadCard } from "@/utils/getIdCard"


export default {
  name: "PhotoList",
  components: { morePics },
  dicts: [
    "sys_diagnosis_status",
    "sys_user_sex",
    "photo_upload_type",
    "photo_lighting_type",
    "sys_face_part",
    "sys_patient_properties",
    "sys_patient_sort",
  ],
  data() {
    return {
      token: this.$store.state.user.token,
      electronUrl: '',
      // 遮罩层
      loading: false,
      imageLoading: false,
      // 总条数
      total: 0,
      // 显示搜索条件
      showSearch: true,
      // 顾客选择弹窗
      patientVisible: false,
      // 登记顾客列表
      patientItem: {
        birthDate: undefined,
        customerSort: undefined,
        diagnosis: undefined,
        deptName: undefined,
        patientId: undefined,
        patientName: undefined,
        patientPhone: undefined,
        properties: undefined,
        sex: undefined,
        status: undefined,

      },
      patientList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        patientId: undefined,
        visitNum: undefined,
        patientName: undefined,
        patientPhone: undefined,
        idNum: undefined,
      },
      pageSizes: [5, 10, 15, 20],

      // 拍摄照片表单
      pictureForm: {
        photoLightingType: "0",
        photoFacePart: '',
        photoUploadType: "霏图",
        leftPhotoAddress: null,
        middlePhotoAddress: null,
        rightPhotoAddress: null,
      },
      leftPaceForm: { avatar: "" },
      leftType: "left",
      centerType: "center",
      rightType: "right",
      uploadPicShow: true,
      centerPaceForm: { avatar: "" },
      rightPaceForm: { avatar: "" },
      // 默认拍照设备
      photoDevice: '0',
      // 补光灯是否开启
      // fillLightDefault: false,
      // 霏图光照类型
      feituLightingType: {
        leftFace: '',
        middleFace: '',
        rightFace: '',
      },
      // 霏图光照和脸部设置
      feituSettingVisible: false,
      feituSettingForm: {
        settingType: '霏图',
        photoQuality: 0.5,
        photoSetting: [
          {
            faceLight: '1',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '1',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '1',
            facePart: '',
            faceUrl: '',
          },
        ]
      },
      feituSettingFormCopy: {},
      feituImageInfo: [
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
      ],
      feituBlobsInDirectory: [],
      photoSettingVisible: false,
      photoSettingForm: {
        settingType: 'VISIA',
        photoQuality: 0.5,
        photoNumber: 15,
        photoSetting: [
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '',
            facePart: '',
            faceUrl: '',
          },
        ]
      },
      photoSettingFormCopy: {},
      VisiaImageInfo: [    // Visia照片信息
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
      ],
      blobsInDirectory: [],
      cameraSettingVisible: false,
      cameraSettingForm: {
        settingType: '照相机',
        photoQuality: 0.5,
        photoNumber: 5,
        photoSetting: [
          {
            faceLight: '1',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '1',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '1',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '1',
            facePart: '',
            faceUrl: '',
          },
          {
            faceLight: '1',
            facePart: '',
            faceUrl: '',
          },

        ]
      },
      cameraSettingFormCopy: {},
      cameraImageInfo: [    // camera照片信息
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },
        {
          faceLight: '',
          facePart: '',
          faceUrl: '',
        },

      ],
      cameraBlobsInDirectory: [],


      uploadPatientId: '',
      morePicsDialogVisible: false,
      photoCount: null,
      timer: null,
      photoPickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }
        ]
      },
      photoUploadTime: new Date(),
      photoUploadTimeStatus: true,
      progress: 0,
      uploadNum: 0,
    }
  },
  computed: {
    ...mapGetters(["avatar", "device", "nickName"]),
    uploadFileLists() {
      return store.getters.uploadFileLists
    },
    MuserInfo() {
      return this.$store.state.app.photoUserInfo
    },
    srcList() {
      return this.VisiaImageInfo.map(n => n.faceUrl) || []
    },
    feituSrcList() {
      return this.feituImageInfo.map(n => n.faceUrl) || []
    },
    cameraSrcList() {
      return this.cameraImageInfo.map(n => n.faceUrl) || []
    },
    // currentTime: function () {
    //   let date = new Date();
    //   let year = date.getFullYear();
    //   let month = date.getMonth() + 1;
    //   let day = date.getDate();
    //   month = month > 9 ? month : "0" + month;
    //   day = day < 10 ? "0" + day : day;
    //   var h = date.getHours();
    //   h = h < 10 ? "0" + h : h;
    //   var minute = date.getMinutes();
    //   minute = minute < 10 ? "0" + minute : minute;
    //   var s = date.getSeconds();
    //   s = s < 10 ? "0" + s : s;
    //   let today = year + '-' + month + '-' + day + " " + h + ':' + minute + ':' + s;
    //   return today;
    // },

  },
  // watch: {
  //   MuserInfo: {
  //     handler(newVal, oldValue) {
  //       const Mdata = newVal
  //       this.queryParams.visitNum = Mdata.visitNum
  //       this.queryParams.patientName = Mdata.patientName
  //       this.queryParams.patientPhone = Mdata.patientPhone
  //       this.queryParams.idNum = Mdata.idNum
  //       if (this.queryParams.visitNum || this.queryParams.patientName || this.queryParams.patientPhone || this.queryParams.idNum) {
  //         this.getPatientList();
  //       }
  //     },
  //     deep: true, // 深度监听
  //     immediate: true,//立即执行
  //   }
  // },
  watch: {
    $route: {
      handler(newVal, oldValue) {
        console.log('$route', newVal)
        if (newVal.query.visitNum) {
          this.queryParams.visitNum = this.$route.query.visitNum
          this.getPatientList();
        }
      },
      deep: true, // 深度监听
      immediate: true,//立即执行
    }
  },

  methods: {
    /** focus获取身份证号 */
    async getSFZToSearch() {
      const res = await startReadCard()
      if (res.result == 3) {
        this.$message.warning('请把身份证放到读卡器上')
        // this.$refs.saveTagInput.blur();
      } else if (res.result == 2) {
        // this.$message.warning('设备不存在')
      } else {
        this.queryParams.idNum = res
      }

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.patientId || this.queryParams.visitNum || this.queryParams.patientName || this.queryParams.patientPhone || this.queryParams.idNum) {
        this.getPatientList();

      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryParams");
      this.resetForm("patientItem");
      this.uploadPatientId = ''
      this.queryParams = {
        pageNum: 1,
        pageSize: 5,
        patientId: '',
        visitNum: '',
        patientName: '',
        patientPhone: '',
        idNum: '',
      }
      this.patientItem = {
        birthDate: undefined,
        customerSort: undefined,
        diagnosis: undefined,
        deptName: undefined,
        patientId: undefined,
        patientName: undefined,
        patientPhone: undefined,
        properties: undefined,
        sex: undefined,
        status: undefined,
      }
    },
    // 真实序号计算（计算分页影响）
    getIndex(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    // 获取病人图片总数量
    // getPhotoCount() {
    //   getPhotoAllCountByPatientId(this.uploadPatientId).then((res) => {
    //     this.photoCount = res.data
    //   })
    // },
    // 获取顾客编号照片总数
    getPhotoCount() {
      getPhotoAllCountByVisitNum(this.patientItem.visitNum).then((res) => {
        console.log('getPhotoCount', res)
        this.photoCount = res.data
      })
      if (this.photoUploadTimeStatus) {
        this.photoUploadTime = new Date()
      }
      // this.progress=0
    },
    closeMorePicsDialog() {
      this.morePicsDialogVisible = false
      this.getPhotoCount()
    },
    // 获取顾客登记列表
    getPatientList() {
      getVisit(this.queryParams).then(
        (response) => {
          if (response.rows.length > 0) {
            if (response.rows.length == 1) {
              this.patientItem = response.rows[0];
              this.patientItem.birthDate = parseInt((new Date() - new Date(this.parseTime(this.patientItem.birthDate))) / (1000 * 60 * 60 * 24 * 365))
              // console.log('this.patientItem++++', this.patientItem)
              this.uploadPatientId = response.rows[0].patientId
              this.getPhotoCount()
            } else {
              this.loading = true

              this.patientVisible = true
              this.patientList = response.rows;
              this.patientList.forEach(item => {
                item.birthDate = parseInt((new Date() - new Date(this.parseTime(item.birthDate))) / (1000 * 60 * 60 * 24 * 365))
              })
              // this.patientList = response.rows[0];
              // this.patientList.birthDate=parseInt((new Date() - new Date(this.parseTime(this.patientList.birthDate))) / (1000 * 60 * 60 * 24 * 365))
              // console.log('this.patientList++++', this.patientList)
              this.total = response.total;
              this.loading = false;
            }


          } else {
            // this.$modal.msgWarning("没找到对应的顾客！");
            this.$confirm('没找到对应的顾客！请您自己搜索选择顾客', '提示', {
              confirmButtonText: '我已知晓',
              cancelButtonText: '取消',
              showCancelButton: false,
              type: 'warning'
            })
              .then((content) => {
                this.resetQuery()
                console.log('content', content)
              })
              .catch((error) => {
                this.resetQuery()
                console.log('error', error)
              })

          }


        }
      )
    },
    confirmPatient(row) {
      this.patientItem = row
      console.log('confirmPatient', row)
      this.patientVisible = false
      this.uploadPatientId = row.patientId
      this.getPhotoCount()
    },

    // goDetail(patientId) {
    //   this.$router.push("/photoWorkstation/photoWorkstation-detail/index/" + patientId);
    // },
    goMorePicture() {
      this.timer = new Date().getTime();
      this.morePicsDialogVisible = true
      // this.$router.push("/photoWorkstation/photoWorkstation-detail/index/" + patientId);
    },
    radioChange(value) {
      console.log('radioChange', value)
      localStorage.setItem('photoDevice', value);
    },
    changeUploadTime() {
      this.photoUploadTimeStatus = false
    },
    // 转换默认拍摄设备
    // turnFillLightDefault(value) {
    //   console.log(value)
    //   localStorage.setItem('fillLightDefault', value);  //进行本地存储
    // },
    uploadFile() {
      this.$refs.fileRef.dispatchEvent(new MouseEvent('click'))
    },
    // fileChange() {
    //   // 上传文件
    // },

    // 霏图光照类型改变
    feituLightingTypeChange(value) {
      var lightTypeNum = ''
      if (value === 'left') {
        lightTypeNum = parseInt(this.feituLightingType.leftFace)
        this.feituLightingType.leftFace = this.dict.type.photo_lighting_type[lightTypeNum].label
      } else if (value === 'middle') {
        lightTypeNum = parseInt(this.feituLightingType.middleFace)
        this.feituLightingType.middleFace = this.dict.type.photo_lighting_type[lightTypeNum].label
      } else if (value === 'right') {
        lightTypeNum = parseInt(this.feituLightingType.rightFace)
        this.feituLightingType.rightFace = this.dict.type.photo_lighting_type[lightTypeNum].label
      }
      console.log('this.feituLightingType', this.feituLightingType)
      localStorage.setItem('feituLightingType', JSON.stringify(this.feituLightingType));

    },
    feituLightingTypeClear(value) {
      if (value === 'left') {
        this.feituLightingType.leftFace = ''
      } else if (value === 'middle') {
        this.feituLightingType.middleFace = ''
      } else if (value === 'right') {
        this.feituLightingType.rightFace = ''
      }
      console.log('this.feituLightingType', this.feituLightingType)
      localStorage.setItem('feituLightingType', JSON.stringify(this.feituLightingType));
    },
    // 打开霏图设备设置
    openFeituSetting() {
      this.feituSettingVisible = true
      this.feituSettingFormCopy = JSON.parse(localStorage.getItem('feituSetting')) || JSON.parse(JSON.stringify(this.feituSettingForm));

    },
    //霏图拍照设置确定
    confirmFeituSetting() {
      console.log('confirmFeituSetting--', this.feituSettingFormCopy)
      if (!this.feituSettingFormCopy.photoQuality) {
        this.$confirm('请输入照片压缩质量!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then((content) => {
            return
          })
          .catch((error) => {
            return
          })
      } else {
        this.feituSettingFormCopy.photoSetting.forEach(item => {
          item.faceUrl = ''
        })
        localStorage.setItem('feituSetting', JSON.stringify(this.feituSettingFormCopy));
        this.feituSettingForm = JSON.parse(JSON.stringify(this.feituSettingFormCopy))
        this.feituImageInfo = this.feituSettingForm.photoSetting
        this.feituBlobsInDirectory = []
        this.feituSettingVisible = false
      }


    },
    //霏图拍照设置取消
    cancelFeituSetting() {
      this.feituSettingVisible = false
    },

    //获取霏图授权,选择照片
    async checkFeituBrowser() {
      // 打开多个文件。
      this.feituBlobsInDirectory = await fileOpen({
        mimeTypes: ['image/*'],
        extensions: ['.ydu'],
        multiple: true,
      });

      console.log('feituBlobsInDirectory---', this.feituBlobsInDirectory);
      if (this.feituBlobsInDirectory[0].name.includes(',')) {
        let firstName = this.feituBlobsInDirectory[0].name
        let firstIndex = firstName.indexOf(",")
        let lastIndex = firstName.indexOf("(")

        let ming = firstName.slice(0, firstIndex)
        let xing = firstName.slice(firstIndex + 1, lastIndex).trim()
        let xingMing = xing + ming
        // console.log('xingMing',xingMing,xingMing.length)
        if (this.patientItem.patientName && this.patientItem.patientName != xingMing) {
          this.$confirm(` 已搜索的顾客姓名是: <strong>(${this.patientItem.patientName})</strong>,  照相机照片的姓名是: <strong>(${xingMing})</strong>,请选择姓名`, '提示', {
            confirmButtonText: `${xingMing}`,
            cancelButtonText: `${this.patientItem.patientName}`,
            type: 'warning',
            dangerouslyUseHTMLString: true,
            center: true,
            confirmButtonClass: 'contrastConfirmButton',
            cancelButtonClass: 'contrastCancelButton',
          })
            .then((content) => {
              this.queryParams.patientName = xingMing
              this.queryParams.patientId = ''
              this.queryParams.idNum = ''
              this.queryParams.visitNum = ''
              this.queryParams.patientPhone = ''
              this.handleQuery()
              // console.log('content', content)
            })
            .catch((error) => {
              // this.resetQuery()
              // console.log('error', error)
            })

        } else if (this.patientItem.patientName && this.patientItem.patientName == xingMing) {

        } else {
          this.queryParams.patientName = xingMing
          // this.queryParams.idNum=''
          // this.queryParams.visitNum=''
          // this.queryParams.patientPhone=''
          this.handleQuery()
        }
      }
      //2.读取文件，成功img标签可以直接使用的格式
      //FileReader类就是专门用来读文件的
      //3.readAsDataURL: dataurl它的本质就是图片的二进制数据， 进行base64加密后形成的一个字符串， 这个字符串可以直接作用img标签的图片资源使用

      this.feituImageInfo.forEach(item => {
        item.faceUrl = ''
      })

      this.feituBlobsInDirectory = this.feituBlobsInDirectory.filter((item, index) => {
        return index < this.feituImageInfo.length
      })

      if (this.photoSettingForm.photoQuality) {

      } else {
        this.photoSettingForm.photoQuality = 0.5
      }
      console.log('this.photoSettingForm.photoQuality', this.photoSettingForm.photoQuality)
      if (this.photoSettingForm.photoQuality == 1) {
        this.feituBlobsInDirectory.forEach((item, index) => {
          const reader = new FileReader();
          reader.readAsDataURL(item)
          reader.onload = () => {
            this.feituImageInfo[index].faceUrl = reader.result
          };
        })
        console.log('this.feituImageInfo=====11111', this.feituImageInfo)

      } else {
        let compress = new imgzip({ quality: this.photoSettingForm.photoQuality });
        let cameraBlob = ''
        let cameraFiles = ''
        let cameraBlobList = []
        let _this = this
        this.feituBlobsInDirectory.forEach((item, index) => {
          compress.photoCompress(item, function (base64) {
            _this.feituImageInfo[index].faceUrl = base64    //预览图片
            // 转 blob 流上传 convertBase64UrlToBlob函数为 imgzip 的静态函数
            cameraBlob = imgzip.convertBase64UrlToBlob(base64);
            cameraFiles = new File([cameraBlob], item.name, { type: 'image/jpeg', lastModified: item.lastModified })

            // console.log('cameraFiles---', cameraFiles)
            cameraBlobList[index] = cameraFiles
            // console.log('blobList---', cameraBlobList)
          });

        })
        this.feituBlobsInDirectory = cameraBlobList
        console.log('this.feituImageInfo=====', this.feituImageInfo)
        console.log('this.feituBlobsInDirectory=====', this.feituBlobsInDirectory)
      }

    },

    // 霏图替换照片
    async replaceFeituImg(index) {
      // 打开一个文件。
      const feituBlob = await fileOpen({
        mimeTypes: ['image/*'],
        extensions: ['.ydu'],
      });
      console.log('feituBlob---', feituBlob);

      // const reader = new FileReader();
      // reader.readAsDataURL(feituBlob);
      // reader.onload = () => {
      //   this.feituImageInfo[index].faceUrl = reader.result
      // };
      // this.feituBlobsInDirectory[index] = feituBlob
      // console.log('feituImageInfo---', this.feituImageInfo)
      // console.log('feituBlobsInDirectory---', this.feituBlobsInDirectory)
      if (this.feituSettingForm.photoQuality) {

      } else {
        this.feituSettingForm.photoQuality = 0.5
      }
      console.log('this.feituSettingForm.photoQuality', this.feituSettingForm.photoQuality)
      if (this.feituSettingForm.photoQuality == 1) {
        const reader = new FileReader();
        reader.readAsDataURL(feituBlob);
        reader.onload = () => {
          this.feituImageInfo[index].faceUrl = reader.result
        };
        this.feituBlobsInDirectory[index] = feituBlob

      } else {
        let compress = new imgzip({ quality: this.feituSettingForm.photoQuality });
        let blob = ''
        let files = ''
        let _this = this
        compress.photoCompress(feituBlob, function (base64) {
          _this.feituImageInfo[index].faceUrl = base64
          // 转 blob 流上传 convertBase64UrlToBlob函数为 imgzip 的静态函数
          blob = imgzip.convertBase64UrlToBlob(base64);
          files = new File([blob], feituBlob.name, { type: 'image/jpeg', lastModified: feituBlob.lastModified })
          _this.feituBlobsInDirectory[index] = files
          // console.log('feituImageInfo---', _this.feituImageInfo)
          // console.log('feituBlobsInDirectory---', _this.feituBlobsInDirectory)
        });
      }

    },
    deleteFeituImg(index) {
      if (this.feituImageInfo[index].faceUrl == '') {
        return
      }
      // console.log(index,this.VisiaImageInfo)
      // this.VisiaImageInfo[index].faceUrl='';
      this.$confirm('此操作将删除该照片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.feituImageInfo[index].faceUrl = '';
          this.feituBlobsInDirectory[index] = '';
          console.log('deleteFeituImg', this.feituImageInfo)
          console.log('deleteFeituImg--', this.feituBlobsInDirectory)
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    submitFeituUpload() {
      if (this.photoUploadTime == null) {
        this.$message.warning('请选择录入日期')
        return
      }
      if (this.uploadPatientId) {
        let faceLightIndex = ''
        faceLightIndex = this.feituImageInfo.findIndex(item => {
          return item.faceLight == ''
        })
        console.log('this.feituImageInfo', this.feituImageInfo)
        console.log('faceLightIndex====', faceLightIndex)
        if (faceLightIndex != -1) {
          this.$confirm(`第<strong>(${faceLightIndex + 1})</strong>张照片的<strong>(光照类型)</strong>未选择！请您选择`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          })
            .then((content) => {
              console.log(content)

            })
            .catch((error) => {
              console.log(error)
            })
          console.log("faceLightIndex----return")
          return

        }

        let facePartIndex = ''
        facePartIndex = this.feituImageInfo.findIndex(item => {
          return item.facePart == ''
        })
        console.log('facePartIndex====', facePartIndex)
        if (facePartIndex != -1) {
          this.$confirm(`第<strong>( ${facePartIndex + 1} )</strong>张照片的<strong>( 部位 )</strong>未选择！请您选择`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          })
            .then((content) => {
              // console.log(content)
            })
            .catch((error) => {
              // console.log(error)
            })
          return
        }

        let faceUrlIndex = ''
        faceUrlIndex = this.feituImageInfo.findIndex(item => {
          return item.faceUrl == ''
        })
        console.log('faceUrlIndex====', faceUrlIndex)
        if (faceUrlIndex != -1) {
          this.$confirm(`第<strong>( ${faceUrlIndex + 1} )</strong>张照片未选择！请您选择`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          })
            .then((content) => {
              // console.log(content)
            })
            .catch((error) => {
              // console.log(error)
            })
          return
        }

        //判断部位
        let photoItem1 = []
        let photoItem2 = []
        let photoItem3 = []
        this.feituImageInfo.forEach(it => {
          if (it.faceLight == '1' && it.facePart == '0') {
            photoItem1.push(it)
          }
          if (it.faceLight == '1' && it.facePart == '1') {
            photoItem2.push(it)
          }
          if (it.faceLight == '1' && it.facePart == '2') {
            photoItem3.push(it)
          }
        })

        if (photoItem1.length == 1 && photoItem2.length == 1 && photoItem3.length == 1) {
          this.confirmFeituUpload()

        } else {
          this.$confirm(`是否修改?使该组照片光照类型为<strong>Standard</strong>,且部位为<strong>左面部, 正面部, 右面部</strong>有且有三张。否则无法进行AI分析!`, '提示', {
            confirmButtonText: '继续上传',
            cancelButtonText: '返回修改',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          }).then((content) => {
            // console.log(content)
            this.confirmFeituUpload()
          }).catch((error) => {
            // console.log(error)
          });
          return
        }

      } else {
        // this.$modal.msgWarning("请选择顾客");
        this.$confirm('请搜索选择顾客！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then((content) => {
            console.log(content)
          })
          .catch((error) => {
            console.log(error)
          })
      }

    },
    async confirmFeituUpload() {
      this.imageLoading = true
      let uuid = nanoid()
      // // 创建FormData对象，通过该对象实现批量文件上传
      // let fd = new FormData()
      // // 因为要上传多个文件，所以需要遍历一下才行,不要直接使用我们的文件数组进行上传，你会发现传给后台的是两个Object
      // this.feituBlobsInDirectory.forEach(function (file) {
      //   // 遍历files数组，将file添加到FormData对象中
      //   fd.append("files", file, file.name)
      //   console.log('fd.append', file, fd.getAll('files'))
      // })

      let faceLights = []
      let faceParts = []
      this.feituImageInfo.forEach(item => {
        faceLights.push(item.faceLight)
        faceParts.push(item.facePart)
      })

      // let Mdata = {
      //   compressionRatio: this.feituSettingForm.photoQuality,
      //   type: this.photoDevice,
      //   patientId: this.uploadPatientId,
      //   visitNum: this.patientItem.visitNum,
      //   status: this.patientItem.status,
      //   // faceLights: faceLights.join(),
      //   // faceParts: faceParts.join(),
      //   // data: fd,
      //   photoUploadTime: this.parseTime(this.photoUploadTime),
      //   uuid: uuid,
      //   num:0
      // }

      let loop = 0
      this.uploadNum = 0
      let fileUploads = []
      for (const i in this.feituImageInfo) {
        let fileId = nanoid()
        let fd = new FormData()
        fd.append("files", this.feituBlobsInDirectory[i], this.feituBlobsInDirectory[i].name)

        const Mdata = {
          compressionRatio: this.feituSettingForm.photoQuality,
          type: this.photoDevice,
          patientId: this.uploadPatientId,
          visitNum: this.patientItem.visitNum,
          status: this.patientItem.status,
          faceLights: faceLights[i],
          faceParts: faceParts[i],
          data: fd,
          photoUploadTime: this.parseTime(this.photoUploadTime),
          uuid: uuid,
          num: i,
        }
        let obj = {
          fileId: fileId,
          progress: 0,
          isUploaded: false
        }
        this.$store.dispatch('file/initUploadFile', obj)
        // uploadPhoto(Mdata, fileId, this).then((response) => {
        //   if (response.code == 200) {
        //     let obj = {
        //       fileId: fileId,
        //       progress: 100,
        //       isUploaded: true
        //     }
        //     this.$store.dispatch('file/uploadUploadFile', obj)
        //     loop += 1
        //     if (loop === this.feituImageInfo.length) {
        //       this.imageLoading = false
        //       this.$store.dispatch('file/clearUploadFile', [])
        //       this.$modal.msgSuccess("提交成功");
        //       this.feituImageInfo.forEach(item => {
        //         item.faceUrl = ''
        //       })
        //       this.feituBlobsInDirectory = []
        //       this.getPhotoCount()
        //     }
        //   }
        // }).catch((error) => {
        //   let obj = {
        //     fileId: fileId,
        //     progress: 0,
        //     isUploaded: false
        //   }
        //   this.$store.dispatch('file/uploadUploadFile', obj)
        //   this.$modal.alertError(error);
        // });
        this.uploadNum = this.feituImageInfo.length
        fileUploads.push(uploadPhoto(Mdata, fileId, this))
        loop += 1
        let bool = (this.feituImageInfo.length === loop)
        // console.log('bool-----',bool)
        if (fileUploads.length === 3 || bool) {
          const res = await Promise.all(fileUploads)
          // console.log("promise all:   ", res)

          res.forEach(col => {
            if (col.code === 200) {
              this.$store.dispatch('file/uploadUploadFile', {
                fileId: col.fileId,
                progress: 100,
                isUploaded: true
              })
            } else {
              this.imageLoading = false
              this.$store.dispatch('file/clearUploadFile', [])
              this.$modal.alertError(error);
              this.getPhotoCount()

            }
          })
          fileUploads = []
          if (bool) {
            this.imageLoading = false
            this.$store.dispatch('file/clearUploadFile', [])
            this.$modal.msgSuccess("提交成功");
            this.feituImageInfo.forEach(item => {
              item.faceUrl = ''
            })
            this.feituBlobsInDirectory = []
            this.getPhotoCount()
          }

        }

      }


    },
    // 打开照相机设置
    openCameraSetting() {
      this.cameraSettingVisible = true
      this.cameraSettingFormCopy = JSON.parse(localStorage.getItem('cameraSetting')) || JSON.parse(JSON.stringify(this.cameraSettingForm));
    },
    // 照相机设备设置
    cameraNumberChange(currentValue, oldValue) {
      var addCameraNum = Math.abs(currentValue - oldValue)
      console.log(addCameraNum, typeof (addCameraNum))
      if (currentValue > oldValue) {
        for (var a = 0; a < addCameraNum; a++) {
          this.cameraSettingFormCopy.photoSetting.push({ faceLight: '1', facePart: '' })
        }
      } else {
        for (var b = 0; b < addCameraNum; b++) {
          this.cameraSettingFormCopy.photoSetting.pop()
        }
      }
    },
    //照相机设置确定
    confirmCameraSetting() {
      if (!this.cameraSettingFormCopy.photoQuality) {
        this.$confirm('请输入照片压缩质量!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then((content) => {
            return
          })
          .catch((error) => {
            return
          })
      } else {
        this.cameraSettingFormCopy.photoSetting.forEach(item => {
          item.faceUrl = ''
        })
        localStorage.setItem('cameraSetting', JSON.stringify(this.cameraSettingFormCopy));
        this.cameraSettingForm = JSON.parse(JSON.stringify(this.cameraSettingFormCopy))
        this.cameraImageInfo = this.cameraSettingForm.photoSetting
        this.cameraBlobsInDirectory = []
        this.cameraSettingVisible = false
      }
    },
    //照相机设置取消
    cancelCameraSetting() {
      this.cameraSettingVisible = false
    },
    //获取照相机授权
    async checkCameraBrowser() {
      // 打开多个文件。
      this.cameraBlobsInDirectory = await fileOpen({
        mimeTypes: ['image/*'],
        extensions: ['.ydu'],
        multiple: true,
      });


      console.log('cameraBlobsInDirectory---', this.cameraBlobsInDirectory);
      if (this.cameraBlobsInDirectory[0].name.includes(',')) {
        let firstName = this.cameraBlobsInDirectory[0].name
        let firstIndex = firstName.indexOf(",")
        let lastIndex = firstName.indexOf("(")

        let ming = firstName.slice(0, firstIndex)
        let xing = firstName.slice(firstIndex + 1, lastIndex).trim()
        let xingMing = xing + ming
        // console.log('xingMing',xingMing,xingMing.length)
        if (this.patientItem.patientName && this.patientItem.patientName != xingMing) {
          this.$confirm(` 已搜索的顾客姓名是: <strong>(${this.patientItem.patientName})</strong>,  照相机照片的姓名是: <strong>(${xingMing})</strong>,请选择姓名`, '提示', {
            confirmButtonText: `${xingMing}`,
            cancelButtonText: `${this.patientItem.patientName}`,
            type: 'warning',
            dangerouslyUseHTMLString: true,
            center: true,
            confirmButtonClass: 'contrastConfirmButton',
            cancelButtonClass: 'contrastCancelButton',
          })
            .then((content) => {
              this.queryParams.patientName = xingMing
              this.queryParams.patientId = ''
              this.queryParams.idNum = ''
              this.queryParams.visitNum = ''
              this.queryParams.patientPhone = ''
              this.handleQuery()
              // console.log('content', content)
            })
            .catch((error) => {
              // this.resetQuery()
              // console.log('error', error)
            })

        } else if (this.patientItem.patientName && this.patientItem.patientName == xingMing) {

        } else {
          this.queryParams.patientName = xingMing
          // this.queryParams.idNum=''
          // this.queryParams.visitNum=''
          // this.queryParams.patientPhone=''
          this.handleQuery()
        }
      }
      //2.读取文件，成功img标签可以直接使用的格式
      //FileReader类就是专门用来读文件的
      //3.readAsDataURL: dataurl它的本质就是图片的二进制数据， 进行base64加密后形成的一个字符串， 这个字符串可以直接作用img标签的图片资源使用

      this.cameraImageInfo.forEach(item => {
        item.faceUrl = ''
      })

      // this.cameraBlobsInDirectory = this.cameraBlobsInDirectory.filter((item, index) => {
      //   return index < this.cameraImageInfo.length
      // })

      // var cameraNum = Math.abs(this.cameraImageInfo.length - this.cameraBlobsInDirectory.length)
      // if (this.cameraImageInfo.length < this.cameraBlobsInDirectory.length) {
      //   for (var a = 0; a < cameraNum; a++) {
      //     this.cameraImageInfo.push({ faceLight: '1', facePart: '', faceUrl: '' })
      //   }
      // } else {
      //   for (var b = 0; b < cameraNum; b++) {
      //     this.cameraImageInfo.pop()
      //   }
      // }
      // 获取照相机设置
      let cameraSettingFormCompare = JSON.parse(localStorage.getItem('cameraSetting')) || this.cameraSettingForm
      let cameraImageInfoCompare = cameraSettingFormCompare.photoSetting
      var cameraNum = Math.abs(this.cameraImageInfo.length - this.cameraBlobsInDirectory.length)
      if (this.cameraImageInfo.length < this.cameraBlobsInDirectory.length && this.cameraImageInfo.length > 5) {
        for (var a = 0; a < cameraNum; a++) {
          this.cameraImageInfo.push({ faceLight: '1', facePart: '', faceUrl: '' })
        }
      } else if (this.cameraImageInfo.length < this.cameraBlobsInDirectory.length) {
        let initLength = this.cameraImageInfo.length
        for (var a = 0; a < cameraNum; a++) {
          if (cameraImageInfoCompare[initLength + a]) {
            this.cameraImageInfo.push({
              faceLight: '1',
              facePart: cameraImageInfoCompare[initLength + a].facePart,
              faceUrl: ''
            })
          } else {
            this.cameraImageInfo.push({ faceLight: '1', facePart: '', faceUrl: '' })
          }
        }
      } else {
        for (var b = 0; b < cameraNum; b++) {
          this.cameraImageInfo.pop()
        }
      }

      // this.cameraBlobsInDirectory.forEach((item, index) => {
      //   const reader = new FileReader();
      //   reader.readAsDataURL(item)
      //   reader.onload = () => {
      //     this.cameraImageInfo[index].faceUrl = reader.result
      //   };
      // })


      if (this.cameraSettingForm.photoQuality) {

      } else {
        this.cameraSettingForm.photoQuality = 0.5
      }
      console.log('this.cameraSettingForm.photoQuality', this.cameraSettingForm.photoQuality)
      if (this.cameraSettingForm.photoQuality == 1) {
        this.cameraBlobsInDirectory.forEach((item, index) => {
          const reader = new FileReader();
          reader.readAsDataURL(item)
          reader.onload = () => {
            this.cameraImageInfo[index].faceUrl = reader.result
          };
        })
        console.log('this.cameraImageInfo=====11111', this.cameraImageInfo)

      } else {
        let compress = new imgzip({ quality: this.cameraSettingForm.photoQuality });
        let cameraBlob = ''
        let cameraFiles = ''
        let cameraBlobList = []
        let _this = this
        this.cameraBlobsInDirectory.forEach((item, index) => {
          compress.photoCompress(item, function (base64) {
            _this.cameraImageInfo[index].faceUrl = base64    //预览图片
            // 转 blob 流上传 convertBase64UrlToBlob函数为 imgzip 的静态函数
            cameraBlob = imgzip.convertBase64UrlToBlob(base64);
            cameraFiles = new File([cameraBlob], item.name, { type: 'image/jpeg', lastModified: item.lastModified })

            // console.log('cameraFiles---', cameraFiles)
            cameraBlobList[index] = cameraFiles
            // console.log('blobList---', cameraBlobList)
          });

        })
        this.cameraBlobsInDirectory = cameraBlobList
        console.log('this.cameraImageInfo=====', this.cameraImageInfo)
        console.log('this.cameraBlobsInDirectory=====', this.cameraBlobsInDirectory)
      }

    },
    // 照相机替换照片
    async replaceCameraImg(index) {
      // 打开一个文件。
      const blobSignalCamera = await fileOpen({
        mimeTypes: ['image/*'],
        extensions: ['.ydu'],
      });
      console.log('blobSignalCamera---', blobSignalCamera);


      if (this.cameraSettingForm.photoQuality) {

      } else {
        this.cameraSettingForm.photoQuality = 0.5
      }
      console.log('this.cameraSettingForm.photoQuality', this.cameraSettingForm.photoQuality)
      if (this.cameraSettingForm.photoQuality == 1) {
        const reader = new FileReader();
        reader.readAsDataURL(blobSignalCamera);
        reader.onload = () => {
          this.cameraImageInfo[index].faceUrl = reader.result
        };
        this.cameraBlobsInDirectory[index] = blobSignalCamera
        // console.log('this.cameraBlobsInDirectory+++++++++',this.cameraBlobsInDirectory)
      } else {
        let compress = new imgzip({ quality: this.cameraSettingForm.photoQuality });
        let cameraBlob = ''
        let cameraFiles = ''
        let _this = this
        compress.photoCompress(blobSignalCamera, function (base64) {
          _this.cameraImageInfo[index].faceUrl = base64
          // 转 blob 流上传 convertBase64UrlToBlob函数为 imgzip 的静态函数
          cameraBlob = imgzip.convertBase64UrlToBlob(base64);
          cameraFiles = new File([cameraBlob], blobSignalCamera.name, {
            type: 'image/jpeg',
            lastModified: blobSignalCamera.lastModified
          })
          _this.cameraBlobsInDirectory[index] = cameraFiles
          // console.log('cameraImageInfo---', _this.cameraImageInfo)
          // console.log('cameraBlobsInDirectory---', _this.cameraBlobsInDirectory)
        });
      }

    },
    // 照相机删除照片
    deleteCameraImg(index) {
      if (this.cameraImageInfo[index].faceUrl == '') {
        return
      }
      // console.log(index,this.VisiaImageInfo)
      // this.VisiaImageInfo[index].faceUrl='';
      this.$confirm('此操作将删除该照片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.cameraImageInfo[index].faceUrl = '';
          this.cameraBlobsInDirectory[index] = '';
          console.log('deleteImg', this.cameraImageInfo)
          console.log('deleteImg--', this.cameraBlobsInDirectory)
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 照相机提交照片
    async submitCameraUpload() {
      if (this.photoUploadTime == null) {
        this.$message.warning('请选择录入日期')
        return
      }
      if (this.uploadPatientId) {
        let faceLightIndex = ''
        faceLightIndex = this.cameraImageInfo.findIndex(item => {
          return item.faceLight == ''
        })
        console.log('this.cameraImageInfo', this.cameraImageInfo)
        console.log('faceLightIndex====', faceLightIndex)
        if (faceLightIndex != -1) {
          this.$confirm(`第<strong>(${faceLightIndex + 1})</strong>张照片的<strong>(光照类型)</strong>未选择！请您选择`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          })
            .then((content) => {
              console.log(content)

            })
            .catch((error) => {
              console.log(error)
            })
          // console.log("faceLightIndex----return")
          return

        }

        let facePartIndex = ''
        facePartIndex = this.cameraImageInfo.findIndex(item => {
          return item.facePart == ''
        })
        console.log('facePartIndex====', facePartIndex)
        if (facePartIndex != -1) {
          this.$confirm(`第<strong>( ${facePartIndex + 1} )</strong>张照片的<strong>( 部位 )</strong>未选择！请您选择`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          })
            .then((content) => {
              // console.log(content)
            })
            .catch((error) => {
              // console.log(error)
            })
          return
        }

        let faceUrlIndex = ''
        faceUrlIndex = this.cameraImageInfo.findIndex(item => {
          return item.faceUrl == ''
        })
        console.log('faceUrlIndex====', faceUrlIndex)
        if (faceUrlIndex != -1) {
          this.$confirm(`第<strong>( ${faceUrlIndex + 1} )</strong>张照片未选择！请您选择`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          })
            .then((content) => {
              // console.log(content)
            })
            .catch((error) => {
              // console.log(error)
            })
          return
        }

        //判断部位
        let photoItem1 = []
        let photoItem2 = []
        let photoItem3 = []
        this.cameraImageInfo.forEach(it => {
          if (it.faceLight == '1' && it.facePart == '0') {
            photoItem1.push(it)
          }
          if (it.faceLight == '1' && it.facePart == '1') {
            photoItem2.push(it)
          }
          if (it.faceLight == '1' && it.facePart == '2') {
            photoItem3.push(it)
          }
        })
        if (photoItem1.length > 1 || photoItem2.length > 1 || photoItem3.length > 1) {
          this.$confirm(`是否修改?使该组照片光照类型为<strong>Standard</strong>,且部位为<strong>左面部, 正面部, 右面部</strong>有且有三张。否则无法进行AI分析!`, '提示', {
            confirmButtonText: '继续上传',
            cancelButtonText: '返回修改',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          }).then((content) => {
            // console.log(content)
            this.confirmCameraUpload()
          }).catch((error) => {
            // console.log(error)
          });
          return
        } else {
          this.confirmCameraUpload()

        }

      } else {
        // this.$modal.msgWarning("请选择顾客");
        this.$confirm('请搜索选择顾客！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then((content) => {
            console.log(content)
          })
          .catch((error) => {
            console.log(error)
          })
      }


    },
    async confirmCameraUpload() {
      this.imageLoading = true
      let uuid = nanoid()

      // // 创建FormData对象，通过该对象实现批量文件上传
      // let fd = new FormData()
      // // 因为要上传多个文件，所以需要遍历一下才行,不要直接使用我们的文件数组进行上传，你会发现传给后台的是两个Object
      // this.cameraBlobsInDirectory.forEach(function (file) {
      //   // 遍历files数组，将file添加到FormData对象中
      //   fd.append("files", file, file.name)
      //   // console.log('fd.append',file,fd.getAll('files'))
      // })

      let faceLights = []
      let faceParts = []
      this.cameraImageInfo.forEach(item => {
        faceLights.push(item.faceLight)
        faceParts.push(item.facePart)
      })


      // -----

      let loop = 0
      this.uploadNum = 0
      let fileUploads = []
      for (const i in this.cameraImageInfo) {
        let fileId = nanoid()
        let fd = new FormData()

        fd.append("files", this.cameraBlobsInDirectory[i], this.cameraBlobsInDirectory[i].name)
        const Mdata = {
          compressionRatio: this.cameraSettingForm.photoQuality,
          type: this.photoDevice,
          patientId: this.uploadPatientId,
          visitNum: this.patientItem.visitNum,
          status: this.patientItem.status,
          faceLights: faceLights[i],
          faceParts: faceParts[i],
          data: fd,
          photoUploadTime: this.parseTime(this.photoUploadTime),
          uuid: uuid,
          num: i,
        }

        let obj = {
          fileId: fileId,
          progress: 0,
          isUploaded: false
        }
        this.$store.dispatch('file/initUploadFile', obj)

        // uploadPhoto(Mdata, fileId, this).then((response) => {
        //   if (response.code == 200) {
        //     let obj = {
        //       fileId: fileId,
        //       progress: 100,
        //       isUploaded: true
        //     }
        //     this.$store.dispatch('file/uploadUploadFile', obj)
        //     loop+=1
        //     if(loop===this.cameraImageInfo.length){
        //       this.imageLoading = false
        //       this.$store.dispatch('file/clearUploadFile', [])
        //       this.$modal.msgSuccess("提交成功");
        //       this.cameraImageInfo.forEach(item => {
        //         item.faceUrl = ''
        //       })
        //       this.cameraBlobsInDirectory = []
        //       this.getPhotoCount()
        //     }
        //   }
        //
        //
        // }).catch((error) => {
        //   let obj = {
        //     fileId: fileId,
        //     progress: 0,
        //     isUploaded: false
        //   }
        //   this.$store.dispatch('file/uploadUploadFile', obj)
        //   this.$modal.alertError(error);
        //   // this.imageLoading = false
        // });
        this.uploadNum = this.cameraImageInfo.length
        fileUploads.push(uploadPhoto(Mdata, fileId, this))
        loop += 1
        let bool = (this.cameraImageInfo.length === loop)
        // console.log('bool-----',bool)
        if (fileUploads.length === 3 || bool) {
          const res = await Promise.all(fileUploads)
          // console.log("promise all:   ", res)

          res.forEach(col => {
            if (col.code === 200) {
              this.$store.dispatch('file/uploadUploadFile', {
                fileId: col.fileId,
                progress: 100,
                isUploaded: true
              })
            } else {
              this.imageLoading = false
              this.$store.dispatch('file/clearUploadFile', [])
              this.$modal.alertError(error);
              this.getPhotoCount()

            }
          })
          fileUploads = []
          if (bool) {
            this.imageLoading = false
            this.$store.dispatch('file/clearUploadFile', [])
            this.$modal.msgSuccess("提交成功");
            this.cameraImageInfo.forEach(item => {
              item.faceUrl = ''
            })
            this.cameraBlobsInDirectory = []
            this.getPhotoCount()
          }

        }

      }
      // console.log('end-------------------------------------------------------')
      // -----


      // uploadPhoto(Mdata,config).then((response) => {
      //   if (response.code == 200) {
      //     console.log(response)
      //     // this.progress=100
      //     this.$modal.msgSuccess("提交成功");
      //     this.cameraImageInfo.forEach(item => {
      //       item.faceUrl = ''
      //     })
      //     this.cameraBlobsInDirectory = []
      //     this.getPhotoCount()
      //     // this.resetQuery()
      //   } else if (response.code = 500) {
      //     this.$modal.alertError(response.msg);
      //   }
      //   this.imageLoading = false
      //
      // }).catch((error) => {
      //   console.log(error)
      //   this.$modal.alertError(error);
      //   this.imageLoading = false
      // });
    },

    // 打开VISIA设备设置
    openPhotoSetting() {
      this.photoSettingVisible = true
      this.photoSettingFormCopy = JSON.parse(localStorage.getItem('visiaSetting')) || JSON.parse(JSON.stringify(this.photoSettingForm));
    },
    // VISIA设备设置
    photoNumberChange(currentValue, oldValue) {
      var addNum = Math.abs(currentValue - oldValue)
      console.log(addNum, typeof (addNum))
      if (currentValue > oldValue) {
        for (var a = 0; a < addNum; a++) {
          this.photoSettingFormCopy.photoSetting.push({ faceLight: '', facePart: '' })
        }
      } else {
        for (var b = 0; b < addNum; b++) {
          this.photoSettingFormCopy.photoSetting.pop()
        }
      }

    },
    //visia设置确定
    confirmSetting() {
      if (!this.photoSettingFormCopy.photoQuality) {
        this.$confirm('请输入照片压缩质量!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then((content) => {
            return
          })
          .catch((error) => {
            return
          })
      } else {
        this.photoSettingFormCopy.photoSetting.forEach(item => {
          item.faceUrl = ''
        })
        localStorage.setItem('visiaSetting', JSON.stringify(this.photoSettingFormCopy));
        this.photoSettingForm = JSON.parse(JSON.stringify(this.photoSettingFormCopy))
        this.VisiaImageInfo = this.photoSettingForm.photoSetting
        this.blobsInDirectory = []
        this.photoSettingVisible = false
      }
    },
    //visia设置取消
    cancelSetting() {
      this.photoSettingVisible = false
    },
    // Visia替换照片
    async replaceImg(index) {
      // 打开一个文件。
      const blobSignal = await fileOpen({
        mimeTypes: ['image/*'],
        extensions: ['.ydu'],
      });
      console.log('blobSignal---', blobSignal);

      // const reader = new FileReader();
      // reader.readAsDataURL(blobSignal);
      // reader.onload = () => {
      //   this.VisiaImageInfo[index].faceUrl = reader.result
      // };
      // this.blobsInDirectory[index] = blobSignal
      if (this.photoSettingForm.photoQuality) {

      } else {
        this.photoSettingForm.photoQuality = 0.5
      }
      console.log('this.photoSettingForm.photoQuality', this.photoSettingForm.photoQuality)
      if (this.photoSettingForm.photoQuality == 1) {
        const reader = new FileReader();
        reader.readAsDataURL(blobSignal);
        reader.onload = () => {
          this.VisiaImageInfo[index].faceUrl = reader.result
        };
        this.blobsInDirectory[index] = blobSignal
      } else {
        let compress = new imgzip({ quality: this.photoSettingForm.photoQuality });
        let blob = ''
        let files = ''
        let _this = this
        compress.photoCompress(blobSignal, function (base64) {
          _this.VisiaImageInfo[index].faceUrl = base64
          // 转 blob 流上传 convertBase64UrlToBlob函数为 imgzip 的静态函数
          blob = imgzip.convertBase64UrlToBlob(base64);
          files = new File([blob], blobSignal.name, { type: 'image/jpeg', lastModified: blobSignal.lastModified })
          _this.blobsInDirectory[index] = files
          console.log('VisiaImageInfo---', _this.VisiaImageInfo)
          console.log('blobsInDirectory---', _this.blobsInDirectory)
        });
      }

    },
    // Visia删除照片
    deleteImg(index) {
      if (this.VisiaImageInfo[index].faceUrl == '') {
        return
      }
      // console.log(index,this.VisiaImageInfo)
      // this.VisiaImageInfo[index].faceUrl='';
      this.$confirm('此操作将删除该照片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.VisiaImageInfo[index].faceUrl = '';
          this.blobsInDirectory[index] = '';
          console.log('deleteImg', this.VisiaImageInfo)
          console.log('deleteImg--', this.blobsInDirectory)
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // Visia获取照片
    async checkBrowser() {
      if (supported) {
        console.log('Using the File System Access API.');
      } else {
        console.log('Using the fallback implementation.');
      }
      // var photoPath=this.photoSettingForm.photoPath.replace(/\\/g,'/')+'/*'
      // console.log('photoPath',photoPath)
      // 打开一个文件。
      // const blob = await fileOpen({
      //   mimeTypes: ['image/*'],
      // });
      //
      // console.log('blob---',blob);
      //
      // const reader = new FileReader();
      // reader.readAsDataURL(blob);
      // reader.onload = () => {
      //   this.VisiaImageInfo.push({url:reader.result})
      // };
      //
      // console.log('reader---',reader)
      // console.log('VisiaImageInfo---',this.VisiaImageInfo)

      // // 打开多个文件。
      // const blobs = await fileOpen({
      //   mimeTypes: ['image/*'],
      //   multiple: true,
      // });
      //
      // console.log('blobs---',blobs);


      // // 打开不同MIME类型的文件。
      // const blobs02 = await fileOpen([
      //   {
      //     description: 'Image files',
      //     mimeTypes: ['image/jpg', 'image/png', 'image/gif', 'image/webp'],
      //     extensions: ['.jpg', '.jpeg', '.png', '.gif', '.webp'],
      //     multiple: true,
      //   },
      //   {
      //     description: 'Text files',
      //     mimeTypes: ['text/*'],
      //     extensions: ['.txt'],
      //   },
      // ]);

      // console.log('blobs02---',blobs02);

      // 打开目录中的所有文件，
      // 递归地包括子目录。
      //1. 拿到里面的文件, 这个file是一个file对象， file对象不能直接展示的
      // this.blobsInDirectory = await directoryOpen({
      //   recursive: true
      // });
      // 打开多个文件。
      this.blobsInDirectory = await fileOpen({
        mimeTypes: ['image/*'],
        extensions: ['.ydu'],
        multiple: true,
      });


      // console.log('blobsInDirectory---', this.blobsInDirectory);
      if (this.blobsInDirectory[0].name.includes(',')) {
        let firstName = this.blobsInDirectory[0].name
        let firstIndex = firstName.indexOf(",")
        let lastIndex = firstName.indexOf("(")

        let ming = firstName.slice(0, firstIndex)
        let xing = firstName.slice(firstIndex + 1, lastIndex).trim()
        let xingMing = xing + ming
        // console.log('xingMing',xingMing,xingMing.length)
        if (this.patientItem.patientName && this.patientItem.patientName != xingMing) {
          this.$confirm(` 已搜索的顾客姓名是: <strong>(${this.patientItem.patientName})</strong>,  VISIA照片的姓名是: <strong>(${xingMing})</strong>,请选择姓名`, '提示', {
            confirmButtonText: `${xingMing}`,
            cancelButtonText: `${this.patientItem.patientName}`,
            type: 'warning',
            dangerouslyUseHTMLString: true,
            center: true,
            confirmButtonClass: 'contrastConfirmButton',
            cancelButtonClass: 'contrastCancelButton',
          })
            .then((content) => {
              this.queryParams.patientName = xingMing
              this.queryParams.patientId = ''
              this.queryParams.idNum = ''
              this.queryParams.visitNum = ''
              this.queryParams.patientPhone = ''
              this.handleQuery()
              // console.log('content', content)
            })
            .catch((error) => {
              // this.resetQuery()
              // console.log('error', error)
            })

        } else if (this.patientItem.patientName && this.patientItem.patientName == xingMing) {

        } else {
          this.queryParams.patientName = xingMing
          // this.queryParams.idNum=''
          // this.queryParams.visitNum=''
          // this.queryParams.patientPhone=''
          this.handleQuery()
        }
      }
      //2.读取文件，成功img标签可以直接使用的格式
      //FileReader类就是专门用来读文件的
      //3.readAsDataURL: dataurl它的本质就是图片的二进制数据， 进行base64加密后形成的一个字符串， 这个字符串可以直接作用img标签的图片资源使用

      this.VisiaImageInfo.forEach(item => {
        item.faceUrl = ''
      })

      this.blobsInDirectory = this.blobsInDirectory.filter((item, index) => {
        return index < this.VisiaImageInfo.length
      })
      // this.blobsInDirectory.forEach((item, index) => {
      //   const reader = new FileReader();
      //   reader.readAsDataURL(item)
      //   reader.onload = () => {
      //     this.VisiaImageInfo[index].faceUrl = reader.result
      //   };
      // })

      if (this.photoSettingForm.photoQuality) {

      } else {
        this.photoSettingForm.photoQuality = 0.5
      }
      console.log('this.photoSettingForm.photoQuality', this.photoSettingForm.photoQuality)
      if (this.photoSettingForm.photoQuality == 1) {
        this.blobsInDirectory.forEach((item, index) => {
          const reader = new FileReader();
          reader.readAsDataURL(item)
          reader.onload = () => {
            this.VisiaImageInfo[index].faceUrl = reader.result
          };
        })
      } else {
        let compress = new imgzip({ quality: this.photoSettingForm.photoQuality });
        let blob = ''
        let files = ''
        let blobList = []
        let _this = this
        this.blobsInDirectory.forEach((item, index) => {
          compress.photoCompress(item, function (base64) {
            _this.VisiaImageInfo[index].faceUrl = base64    //预览图片
            // 转 blob 流上传 convertBase64UrlToBlob函数为 imgzip 的静态函数
            blob = imgzip.convertBase64UrlToBlob(base64);
            files = new File([blob], item.name, { type: 'image/jpeg', lastModified: item.lastModified })
            // console.log('blob---',blob)
            console.log('files---', files)
            blobList[index] = files
            console.log('blobList---', blobList)
          });

        })
        this.blobsInDirectory = blobList
        console.log('this.VisiaImageInfo=====', this.VisiaImageInfo)
      }


    },

    // Visia提交照片
    async submitVisiaUpload() {
      if (this.photoUploadTime == null) {
        this.$message.warning('请选择录入日期')
        return
      }
      if (this.uploadPatientId) {
        let faceLightIndex = ''
        faceLightIndex = this.VisiaImageInfo.findIndex(item => {
          return item.faceLight == ''
        })
        console.log('this.VisiaImageInfo', this.VisiaImageInfo)
        console.log('faceLightIndex====', faceLightIndex)
        if (faceLightIndex != -1) {
          this.$confirm(`第<strong>(${faceLightIndex + 1})</strong>张照片的<strong>(光照类型)</strong>未选择！请您选择`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          })
            .then((content) => {
              console.log(content)

            })
            .catch((error) => {
              console.log(error)
            })
          // console.log("faceLightIndex----return")
          return

        }

        let facePartIndex = ''
        facePartIndex = this.VisiaImageInfo.findIndex(item => {
          return item.facePart == ''
        })
        console.log('facePartIndex====', facePartIndex)
        if (facePartIndex != -1) {
          this.$confirm(`第<strong>( ${facePartIndex + 1} )</strong>张照片的<strong>( 部位 )</strong>未选择！请您选择`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          })
            .then((content) => {
              // console.log(content)
            })
            .catch((error) => {
              // console.log(error)
            })
          return
        }

        let faceUrlIndex = ''
        faceUrlIndex = this.VisiaImageInfo.findIndex(item => {
          return item.faceUrl == ''
        })
        console.log('faceUrlIndex====', faceUrlIndex)
        if (faceUrlIndex != -1) {
          this.$confirm(`第<strong>( ${faceUrlIndex + 1} )</strong>张照片未选择！请您选择`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          })
            .then((content) => {
              // console.log(content)
            })
            .catch((error) => {
              // console.log(error)
            })
          return
        }

        //判断部位
        let photoItem1 = []
        let photoItem2 = []
        let photoItem3 = []
        this.VisiaImageInfo.forEach(it => {
          if (it.faceLight == '1' && it.facePart == '0') {
            photoItem1.push(it)
          }
          if (it.faceLight == '1' && it.facePart == '1') {
            photoItem2.push(it)
          }
          if (it.faceLight == '1' && it.facePart == '2') {
            photoItem3.push(it)
          }
        })
        if (photoItem1.length > 1 || photoItem2.length > 1 || photoItem3.length > 1) {
          this.$confirm(`是否修改?使该组照片光照类型为<strong>Standard</strong>,且部位为<strong>左面部, 正面部, 右面部</strong>有且有三张。否则无法进行AI分析!`, '提示', {
            confirmButtonText: '继续上传',
            cancelButtonText: '返回修改',
            type: 'warning',
            dangerouslyUseHTMLString: true,
          }).then((content) => {
            // console.log(content)
            this.confirmVisiaUpload()
          }).catch((error) => {
            // console.log(error)
          });
          return
        } else {
          this.confirmVisiaUpload()
        }

      } else {
        // this.$modal.msgWarning("请选择顾客");
        this.$confirm('请搜索选择顾客！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then((content) => {
            console.log(content)
          })
          .catch((error) => {
            console.log(error)
          })
      }


    },
    async confirmVisiaUpload() {
      this.imageLoading = true
      let uuid = nanoid()
      // // 创建FormData对象，通过该对象实现批量文件上传
      // let fd = new FormData()
      // // 因为要上传多个文件，所以需要遍历一下才行,不要直接使用我们的文件数组进行上传，你会发现传给后台的是两个Object
      // this.blobsInDirectory.forEach(function (file) {
      //   // 遍历files数组，将file添加到FormData对象中
      //   fd.append("files", file, file.name)
      //   // console.log('fd.append',file,fd.getAll('files'))
      // })

      let faceLights = []
      let faceParts = []
      this.VisiaImageInfo.forEach(item => {
        faceLights.push(item.faceLight)
        faceParts.push(item.facePart)
      })


      let loop = 0
      this.uploadNum = 0
      let fileUploads = []
      for (const i in this.VisiaImageInfo) {
        let fileId = nanoid()
        let fd = new FormData()
        fd.append("files", this.blobsInDirectory[i], this.blobsInDirectory[i].name)
        const Mdata = {
          compressionRatio: this.photoSettingForm.photoQuality,
          type: this.photoDevice,
          patientId: this.uploadPatientId,
          visitNum: this.patientItem.visitNum,
          status: this.patientItem.status,
          faceLights: faceLights[i],
          faceParts: faceParts[i],
          data: fd,
          photoUploadTime: this.parseTime(this.photoUploadTime),
          uuid: uuid,
          num: i,
        }

        let obj = {
          fileId: fileId,
          progress: 0,
          isUploaded: false
        }
        this.$store.dispatch('file/initUploadFile', obj)
        // uploadPhoto(Mdata, fileId, this).then((response) => {
        //   if (response.code == 200) {
        //     let obj = {
        //       fileId: fileId,
        //       progress: 100,
        //       isUploaded: true
        //     }
        //     this.$store.dispatch('file/uploadUploadFile', obj)
        //     loop += 1
        //     if (loop === this.VisiaImageInfo.length) {
        //       this.imageLoading = false
        //       this.$store.dispatch('file/clearUploadFile', [])
        //       this.$modal.msgSuccess("提交成功");
        //       this.VisiaImageInfo.forEach(item => {
        //         item.faceUrl = ''
        //       })
        //       this.blobsInDirectory = []
        //       this.getPhotoCount()
        //     }
        //   }
        // }).catch((error) => {
        //   let obj = {
        //     fileId: fileId,
        //     progress: 0,
        //     isUploaded: false
        //   }
        //   this.$store.dispatch('file/uploadUploadFile', obj)
        //   this.$modal.alertError(error);
        //   // this.imageLoading = false
        // });
        this.uploadNum = this.VisiaImageInfo.length
        fileUploads.push(uploadPhoto(Mdata, fileId, this))
        loop += 1
        let bool = (this.VisiaImageInfo.length === loop)
        // console.log('bool-----',bool)
        if (fileUploads.length === 3 || bool) {
          const res = await Promise.all(fileUploads)
          // console.log("promise all:   ", res)

          res.forEach(col => {
            if (col.code === 200) {
              this.$store.dispatch('file/uploadUploadFile', {
                fileId: col.fileId,
                progress: 100,
                isUploaded: true
              })
            } else {
              this.imageLoading = false
              this.$store.dispatch('file/clearUploadFile', [])
              this.$modal.alertError(error);
              this.getPhotoCount()

            }
          })
          fileUploads = []
          if (bool) {
            this.imageLoading = false
            this.$store.dispatch('file/clearUploadFile', [])
            this.$modal.msgSuccess("提交成功");
            this.VisiaImageInfo.forEach(item => {
              item.faceUrl = ''
            })
            this.blobsInDirectory = []
            this.getPhotoCount()
          }
        }

      }
    },
    goNewPage() {
      // if (this.uploadPatientId) {
      //   this.electronUrl = `electron-vue-camera://startapp?token=${this.token}&&visitNum=${this.patientItem.visitNum}`
      //   window.open(this.electronUrl)
      // } else {
      //   this.$confirm('请搜索选择顾客！', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   })
      //     .then((content) => {
      //       console.log(content)
      //     })
      //     .catch((error) => {
      //       console.log(error)
      //     })
      // }
      if (!this.uploadPatientId) {
        this.patientItem.visitNum = ''
      }
      this.electronUrl = `electron-vue-camera://startapp?token=${this.token}&&visitNum=${this.patientItem.visitNum}`
      window.open(this.electronUrl)
    }

  },

  created() {
    // 获取拍照设备
    this.photoDevice = localStorage.getItem('photoDevice') || '0'
    // 获取补光灯是否开启
    // this.fillLightDefault = localStorage.getItem('fillLightDefault')
    // 获取霏图光照类型

    this.feituSettingForm = JSON.parse(localStorage.getItem('feituSetting')) || this.feituSettingForm
    this.feituImageInfo = this.feituSettingForm.photoSetting
    // console.log('this.feituSettingForm',this.feituSettingForm)

    // 获取visia设置
    this.photoSettingForm = JSON.parse(localStorage.getItem('visiaSetting')) || this.photoSettingForm
    this.VisiaImageInfo = this.photoSettingForm.photoSetting
    // console.log('this.photoSettingForm',this.photoSettingForm)

    // 获取照相机设置
    this.cameraSettingForm = JSON.parse(localStorage.getItem('cameraSetting')) || this.cameraSettingForm
    this.cameraImageInfo = this.cameraSettingForm.photoSetting
    // console.log('this.cameraSettingForm',this.cameraSettingForm)

    this.loading = false
  }


}

</script>
<style scoped rel="stylesheet/scss" lang="scss">
.formBox {
  box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.2);
  border-radius: 4px 4px 4px 4px;
  padding: 20px;
  margin-bottom: 10px;
}

.formBox .el-form-item {
  margin-bottom: 10px;
}

.progressBox {
  width: 60%;
  z-index: 999999;
  position: absolute;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);

  //box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.3);
  //background: #fff;
  //border-radius: 10px;
  //padding: 20px ;
  .lineTitle {
    text-align: center;
    font-size: 20px;
    color: #46A6FF;
  }

  .lineBox {
    display: flex;
    align-items: center;
    margin-top: 6px;

    .indexBox {
      width: 26px;
      color: #1890ff;
    }

    .el-progress {
      width: 100%;

    }
  }

}


.contentBox {
  display: flex;
  justify-content: space-between;
  /*align-items: center;*/
  padding-bottom: 10px;
}

.contentBox .contentBoxRight {
  display: flex;
  align-items: center;
}

.contentBox .contentBoxLeft {
  display: flex;
  align-items: center;
}

.contentBox .line {
  display: inline-block;
  width: 6px;
  height: 23px;
  background: #5972FF;
  border-radius: 10px;
  margin-right: 12px;
}

.contentBox .name {
  font-size: 18px;

}

.patientBox {
  .itemBox {
    display: flex;
    box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.2);
    border-radius: 4px 4px 4px 4px;
    padding: 20px;

    .itemInfoBox {
      display: flex;

    }
  }
}

.user-info-head {
  position: relative;
  display: inline-block;
  width: 200px;
  height: 317px;
  border: 1px solid #000;

  .rightNum {
    position: absolute;
    top: 0;
    right: 0;
    width: 20px;
    height: 20px;
    color: red;
    font-weight: bold;
    opacity: 1;
  }

  .rightIcon {
    position: absolute;
    top: 0;
    right: 0;
    width: 20px;
    height: 20px;
    color: red;
    font-weight: bold;
    opacity: 0;
  }

  .leftEnlarge {
    position: absolute;
    top: 0;
    left: 0;
    width: 30px;
    height: 30px;
    color: red;
    opacity: 0;
  }

  .img-style {
    width: 100%;
    height: 100%;

    ::v-deep .el-image__error {
      opacity: 0;
    }
  }

  //image图片路径错误时，不显示破图/图片裂开，
  //.img-style[src=""],
  //.img-style:not([src]) {
  //  opacity: 0;
  //}
  &:hover {
    .rightNum {
      opacity: 0;
    }

    .rightIcon {
      opacity: 1;
    }

    .leftEnlarge {
      opacity: 1;
    }

  }
}


::v-deep .labelBox {
  label {
    position: relative;
  }

  #fileinp {
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;
  }

  #btn {
    padding: 5px 10px;
    background: #f3a4a1;
    color: #FFF;
    border: none;
    border-radius: 5px;
    margin-right: 5px;
  }

}

::v-deep .el-input.is-disabled .el-input__inner {
  color: #606266;
}

::v-deep .el-textarea.is-disabled .el-textarea__inner {
  color: #606266;
}

//::v-deep .el-loading-spinner {
//  /*这个是自己想设置的 gif 加载动图*/
//  background-image: url('../../../assets/images/loading.gif');
//  background-repeat: no-repeat;
//  /*background-size: 200px 120px;*/
//  background-size: 200px 150px;
//  height: 150px;
//  width: 100%;
//  background-position: center;
//  /*覆盖 element-ui  默认的 50%    因为此处设置了height:100%,所以不设置的话，会只显示一半，因为被top顶下去了*/
//  top: 10%;
//}
::v-deep .formBox .el-loading-spinner {
  display: none;
}

::v-deep .formBox .el-loading-spinner .circular {
  /*隐藏 之前  element-ui  默认的 loading 动画*/
  display: none;
}

::v-deep .formBox .el-loading-spinner .el-loading-text {
  /*为了使得文字在loading图下面*/
  margin: 100px 0px;
  //font-size: 20px;
}

::v-deep .el-dialog {
  margin-top: 0 !important;
}

::v-deep .el-dialog:not(.is-fullscreen) {
  margin-top: 0 !important;
}
</style>

